package controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.convert.Convert;
import com.jfinal.aop.Inject;
import com.jfinal.ext.cors.EnableCORS;
import com.jfinal.plugin.activerecord.Page;
import common.Result;
import io.jboot.db.model.Columns;
import model.User;
import service.UserService;
import io.jboot.web.controller.JbootController;
import io.jboot.web.controller.annotation.RequestMapping;
import io.jboot.web.json.JsonBody;

import java.util.Date;
import java.util.Map;

/**
 * @author: 孙先生
 * @createTime: 2023/05/24 23:20
 * @description: 用户控制类
 */
@RequestMapping(value = "/user")
@EnableCORS
public class UserController extends JbootController {

    @Inject
    private UserService userService;

    /**
     * 分页获取用户数据
     *
     * @return
     */
    public Result<Page<User>> page() {
        // 获取请求参数
        Map<String, String> paras = getParas();
        Columns columns = new Columns();
        if (paras.get("name") != null) {
            columns.like("name", "%" + paras.get("name") + "%");
        }
        return Result.success(
                userService.paginateByColumns(
                        Convert.toInt(paras.get("pageNum"), 1),
                        Convert.toInt(paras.get("pageSize"), 20),
                        columns)
        );
    }

    public Result<String> add(@JsonBody User user) {
        user.setCreateTime(new Date());
        user.setUpdateTime(new Date());
        Columns columns = new Columns();
        columns.eq("username", user.getUsername());
        long count = user.findCountByColumns(columns);
        if (count > 0) return Result.fail("用户名已存在");
        Object save = user.save();
        if (BeanUtil.isNotEmpty(save)) {
            return Result.success();
        } else {
            return Result.fail("新增失败");
        }
    }

    public Result<String> update(@JsonBody User user) {
        user.setUpdateTime(new Date());
        boolean res = user.update();
        if (res) {
            return Result.success();
        } else {
            return Result.fail("修改失败");
        }
    }

    public Result<String> delete() {
        Map<String, String> paras = getParas();
        boolean res = userService.batchDeleteByIds(paras.get("ids"));
        if (res) {
            return Result.success();
        } else {
            return Result.fail("删除失败");
        }
    }
}
